import redis.asyncio as redis
import settings
from typing import Any
import json

class ZLRedis:
    user_prefix: str = "user"

    def __init__(self):
        self.client: redis.Redis = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, decode_responses=True)

    async def set(self, key, value, ex: int):
        await self.client.set(key, value, ex=ex if ex else None)

    async def set_dict(self, key: str, value: dict, ex: int=5*60*60):
        await self.set(key, json.dumps(value), ex=ex if ex else None)

    async def get(self, key):
        value = await self.client.get(key)
        return value

    async def get_dict(self, key: str):
        value = await self.get(key)
        return json.loads(value) if value else None

    async def delete(self, key):
        await self.client.delete(key)

    async def decrease(self, key, amount=1):
        await self.client.decrby(key, amount)

    async def increase(self, key, amount=1):
        await self.client.incrby(key, amount)

    async def close(self):
        await self.client.aclose()

    def _user_key(self, sender_staff_id: str):
        return f"{self.user_prefix}:{sender_staff_id}"

    async def set_user(self, sender_staff_id: str, user_info: dict[str, Any]):
        await self.set_dict(self._user_key(sender_staff_id), user_info)

    async def get_user(self, sender_staff_id: str):
        return await self.get_dict(sender_staff_id)